package com.cmsky.open.user.manager;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cmsky.open.core.base.*;

import com.cmsky.open.user.model.*;
import com.cmsky.open.user.dao.*;
import com.cmsky.open.user.enums.UserState;
import com.cmsky.open.user.exception.UserException;
import com.cmsky.open.user.exception.UserNotFoundExcetion;
import com.cmsky.open.user.exception.UserStateNotValidException;
import com.cmsky.open.user.vo.query.*;

/**
 * @author jandyfish email:jandyfish(a)gmail.com
 * @version 1.0
 * @since 1.0
 */


@Service
@Transactional
public class UserMoneyInfoManager extends BaseManager<UserMoneyInfo,java.lang.Integer>{

	private UserMoneyInfoDao userMoneyInfoDao;
	private UserInfoDao userInfoDao;
	
	/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写*/
	public void setUserMoneyInfoDao(UserMoneyInfoDao dao) {
		this.userMoneyInfoDao = dao;
	}
	
	public void setUserInfoDao(UserInfoDao userInfoDao) {
		this.userInfoDao = userInfoDao;
	}

	public EntityDao getEntityDao() {
		return this.userMoneyInfoDao;
	}
	
	@Transactional(readOnly=true)
	public BasePager findPage(UserMoneyInfoQuery query) {
		return userMoneyInfoDao.findPage(query);
	}
	
	/** 插入数据 ,分布式情况下需加锁*/
	@Transactional
	public synchronized int save(UserMoneyInfo entity) throws DataAccessException{
		int count = getEntityDao().save(entity);
		if(count > 0){
			UserInfo user = (UserInfo) userInfoDao.getById(entity.getUserId());
			if(null == user){
				throw new UserNotFoundExcetion(entity.getUserId().toString());
			}else if(UserState.Configed != UserState.getByValue(user.getState())){
				throw new UserStateNotValidException(user.getName());
			}
			user.setMoney(entity.getMoney()+user.getMoney());
			if(1 != this.userInfoDao.update(user)){
				throw new UserException("没有更新用户");
			}
		}
		return count;
	}
	
	@Override
	public int saveOrUpdate(UserMoneyInfo entity) throws DataAccessException {
		if(null == entity.getId() || 0 >= entity.getId()){
			return this.save(entity);
		}else{
			return this.update(entity);
		}
	}
}
